using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.Json;
using MVCWeekOne.Models;

namespace MVCWeekOne.Controllers
{
    public class RoleController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ApiSettings _apiSettings;

        public RoleController(IHttpClientFactory httpClientFactory, IOptions<ApiSettings> apiSettings)
        {
            _httpClientFactory = httpClientFactory;
            _apiSettings = apiSettings.Value;
        }

        [HttpGet]
        public async Task<IActionResult> RoleManagement()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return RedirectToAction("Login", "Account");
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Role/GetRolePage?Index=1&Size=10");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var roleResult = JsonSerializer.Deserialize<ApiPageing<RoleDto>>(result);
                    
                    if (roleResult != null)
                    {
                        return View(roleResult.Items);
                    }
                }

                return View(new List<RoleDto>());
            }
            catch
            {
                return View(new List<RoleDto>());
            }
        }

        /// <summary>
        /// 获取角色分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetRolePage(int page = 1, int limit = 10, string roleName = "")
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { code = 1, msg = "未登录", count = 0, data = new List<RoleDto>() });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 构建查询参数 - Layui传递的是page和limit，我们需要转换为Index和Size
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(roleName))
                    queryParams.Add($"RoleName={Uri.EscapeDataString(roleName)}");
                
                queryParams.Add($"Index={page}");
                queryParams.Add($"Size={limit}");
                
                var queryString = string.Join("&", queryParams);
                var url = $"{_apiSettings.ReadApiUrl}/Role/GetRolePage?{queryString}";

                var response = await client.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    
                    var roleResult = JsonSerializer.Deserialize<ApiPageing<RoleDto>>(result);
                    
                    if (roleResult != null)
                    {
                        return Json(new { 
                            code = 0, 
                            msg = "success", 
                            count = roleResult.TotaCount,
                            data = roleResult.PageData ?? new List<RoleDto>()
                        });
                    }
                }


                return Json(new { code = 1, msg = "获取角色数据失败", count = 0, data = new List<RoleDto>() });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"获取角色数据异常: {ex.Message}", count = 0, data = new List<RoleDto>() });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetRoleById(long roleId)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                // 通过分页接口获取角色信息，然后筛选出指定角色
                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Role/GetRolePage?Index=1&Size=1000");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var roleResult = JsonSerializer.Deserialize<ApiPageing<RoleDto>>(result);
                    
                    if (roleResult?.PageData != null)
                    {
                        var role = roleResult.PageData.FirstOrDefault(r => r.Id == roleId);
                        
                        if (role != null)
                        {
                            return Json(new { success = true, data = role });
                        }
                        else
                        {
                            return Json(new { success = false, message = "角色不存在" });
                        }
                    }
                }

                return Json(new { success = false, message = "获取角色信息失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取角色信息失败: {ex.Message}" });
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetPermissions()
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.GetAsync($"{_apiSettings.ReadApiUrl}/Permission/GetAllPermission");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var permissionResult = JsonSerializer.Deserialize<ApiResult<List<PermissionModel>>>(result);
                    
                    if (permissionResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, data = permissionResult.Data });
                    }
                }

                return Json(new { success = false, message = "获取权限数据失败" });
            }
            catch
            {
                return Json(new { success = false, message = "获取权限数据失败" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> AddRole([FromBody] AddRoleViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var roleData = new
                {
                    RoleName = model.RoleName,
                    PermissionIds = model.PermissionIds
                };

                var json = JsonSerializer.Serialize(roleData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync($"{_apiSettings.WriteApiUrl}/Role/Add", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var addResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (addResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = addResult.Msg ?? "添加成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = addResult?.Msg ?? "添加失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = $"API调用失败: {response.StatusCode}, {errorContent}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"添加失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> UpdateRole([FromBody] UpdateRoleViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                // 添加调试信息
                System.Diagnostics.Debug.WriteLine($"UpdateRole - 接收到的数据: RoleId={model.RoleId}, RoleName={model.RoleName}, PermissionIds={string.Join(",", model.PermissionIds ?? new List<long>())}");

                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var roleData = new
                {
                    RoleId = model.RoleId,
                    RoleName = model.RoleName,
                    PermissionIds = model.PermissionIds
                };

                var json = JsonSerializer.Serialize(roleData);
                System.Diagnostics.Debug.WriteLine($"UpdateRole - 发送给后端的数据: {json}");
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PutAsync($"{_apiSettings.WriteApiUrl}/Role/Update", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var updateResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (updateResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = updateResult.Msg ?? "更新成功" });
                    }
                    else
                    {
                        return Json(new { success = false, message = updateResult?.Msg ?? "更新失败" });
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return Json(new { success = false, message = $"API调用失败: {response.StatusCode}, {errorContent}" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"更新失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> DeleteRole([FromBody] DeleteRoleViewModel model)
        {
            var token = HttpContext.Session.GetString("Token");
            if (string.IsNullOrEmpty(token))
            {
                return Json(new { success = false, message = "未登录" });
            }

            try
            {
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await client.DeleteAsync($"{_apiSettings.WriteApiUrl}/Role/Delete?RoleId={model.RoleId}");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    var deleteResult = JsonSerializer.Deserialize<ApiResult<int>>(result);
                    
                    if (deleteResult?.IsSuccess == true)
                    {
                        return Json(new { success = true, message = "删除成功" });
                    }
                }

                return Json(new { success = false, message = "删除失败" });
            }
            catch
            {
                return Json(new { success = false, message = "删除失败" });
            }
        }
    }
}
